﻿using System.Linq;

namespace Borg.Framework
{
    public static class PreferencesStartup
    {
        private static bool _done;

        private static void PersistorRegistered(object sender, RegisterEventArgs args)
        {
            if (!_done)
            {
                args.PlugTypeInfo.ExtensionTypeInfo.GetSharedExtension(true);
                _done = true;
            }

            args.SlotInfo.SlotTypeInfo.Registered -= PersistorRegistered;
        }

        private static void PluginAdded(object sender, PluginEventArgs args)
        {
            if (_done)
                Runtime.Repository.PluginAdded -= PluginAdded;

            foreach (var sti in
                from eti in args.ExtensionTypeInfos
                from sti in eti.SlotTypeInfos
                where sti.Name.Equals("Borg.Preferences")
                select sti)
                sti.Registered += PersistorRegistered;
        }

        public static void Register()
        {
            Runtime.Repository.PluginAdded += PluginAdded;

            foreach (var sti in Runtime.Repository.SlotTypeInfos.
                Where(sti => sti.Name.Equals("Borg.Preferences")))
                sti.Registered += PersistorRegistered;
        }
    }
}

